<?php

namespace Admin\Controller;

use Core\Controller\AdminBaseController;
use Core\Exception\BusinessException;
use Core\Session\AdminSessionHelper;
use Exception;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;

class CatalogController extends AdminBaseController {

    public function indexAction() {

    }

    public function countryAction(){

    }


    public function countryListAction(){
        $countryTable = $this->getTableFinder()->getCountryTable();

        //paging info
        $page = $this->params()->fromPost('page');
        $pageSize = $this->params()->fromPost('pageSize');
        $offset = ($page - 1)*$pageSize;

        //criteria info
        $name = $this->params()->fromPost('name');

        $allCountry = $countryTable->searchAllCountry(true, $offset, $pageSize, null, array('name'=>$name));


        $result = new JsonModel(array(
            'rows' => $allCountry['rows']->toArray(),
            'total' => $allCountry['total'],
            'success'=>true,
        ));

        return $result;

    }

    public function countryAddAction(){
        try{
            $code = $this->params()->fromPost('code');
            $name = $this->params()->fromPost('name');
            $data = array('code'=>$code,'name'=>$name);
            $countryTable = $this->getTableFinder()->getCountryTable();
            $id = $countryTable->insert($data);
            $result = new JsonModel( array(
                'success'=>true,'id'=>$id
            ));

            return $result;
        }catch (Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }

    public function countryUpdateAction(){
        try{
            $code = $this->params()->fromPost('code');
            $name = $this->params()->fromPost('name');
            $id = $this->params()->fromPost('id');
            $data = array('code'=>$code,'name'=>$name);
            $countryTable = $this->getTableFinder()->getCountryTable();
            $countryTable->update($data,$id);
            $result = new JsonModel( array(
                'success'=>true,
            ));

            return $result;
        }catch (Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }

    public function countryRemoveAction(){
        try{
            $id = $this->params()->fromPost('id');

            $countryTable = $this->getTableFinder()->getCountryTable();
            $countryTable->delete($id);
            $result = new JsonModel( array(
                'success'=>true,
            ));
            return $result;
        }catch (Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }
//----------------------------for category part-----------------------------------

    public function categoryAction(){
        try{
            $categoryTable = $this->getTableFinder()->
                getCategoryTable(AdminSessionHelper::getCurrentLang());
            return new ViewModel(array('categoryGroups'=>$categoryTable->getAllCategoryGroup()));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function categoryListAction(){
        try{

            $categoryId = $this->params()->fromPost('id');
            $categoryTable = $this->getTableFinder()->getCategoryTable(
                AdminSessionHelper::getCurrentLang());
            $category_Item = $categoryTable->getCategory($categoryId);
            $categoryAsKendoDataSourceArr = $categoryTable->getCategoryAsKendoDataSource($category_Item->group_code);
            return new JsonModel($categoryAsKendoDataSourceArr);
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function getCategoryGroupContentAction(){
        $viewModel = new ViewModel();
        $viewModel->setTerminal(true);
        $groupCode = $this->params()->fromPost('groupCode');
        $viewModel->setVariable('groupCode', $groupCode);

        $categoryTable = $this->getTableFinder()->getCategoryTable(
            AdminSessionHelper::getCurrentLang());
        $categoryAsKendoDataSourceArr = $categoryTable->getCategoryAsKendoDataSource($groupCode);
        $viewModel->setVariable('categoryAsKendoDataSourceArr',$categoryAsKendoDataSourceArr);

        $rootCategory = $categoryTable->getRootCategory($groupCode);
        $viewModel->setVariable('rootCategory',$rootCategory);


        return $viewModel;
    }

    public function categoryComboAction(){
        try{

            $groupCode = $this->params()->fromPost('groupCode');

            $searchOption=array("groupCode"=>$groupCode);

            $categoryTable = $this->getTableFinder()->getCategoryTable(
                AdminSessionHelper::getCurrentLang());
            $tmp = $categoryTable->searchCategory(false, null, null, array(), $searchOption);
            $result = $this->buidTreeForCombo($tmp->toArray());
            return new JsonModel($result);
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }
    private function buidTreeForCombo($rows){

        $right = array();
        $result = array();

        foreach ($rows as $item) {
            $item["text"] = $item["name"];

            if(count($right)>0){
                while ($right[count($right)-1]['rgt']<$item['rgt']) {
                    array_pop($right);
                }
            }
            if($item['lft'] < $item['rgt'] -1){

                $item["children"] = array();
            }
            if(count($right)>0){
                $latestHasChildren = &$this->findLatestHasChildren($result[(count($result)-1)], $right[count($right)-1]);

                $latestHasChildren["children"][] =  $item;

            }else{
                call_user_func_array("array_push", array(&$result,&$item));
            }

            call_user_func_array("array_push", array(&$right,&$item));

        }
        return $result;
    }

    private function &findLatestHasChildren(&$arr, $sample){

        if(array_key_exists("children",$arr)){
            if(count($arr["children"]) == 0 || !array_key_exists("children",$arr["children"][count($arr["children"]) -1]) ){
                return $arr;
            }elseif(array_key_exists("children",$arr["children"][count($arr["children"]) -1])
                && $arr["children"][count($arr["children"]) -1]["rgt"] < $sample["rgt"]){
                return $arr;
            }
            else {
                return $this->findLatestHasChildren($arr["children"][count($arr["children"]) -1],$sample);
            }
        }
        else{
            return $arr;
        }
    }


    public function getCategoryParentAction(){
        try{

            $id = $this->params()->fromPost('id');
            if(!$id){
                throw new BusinessException("Chưa truyền id!");
            }

            $categoryTable = $this->getTableFinder()->getCategoryTable(
                AdminSessionHelper::getCurrentLang());
            $category_Item = $categoryTable->getCategory($id);
            $directParent = $category_Item->getDirectParent();
            if(!$directParent)
                return new JsonModel(array('success'=>true, "upable"=>false, "downable"=>false));
            else{
                $upable = true;
                $downable = true;

                if($directParent->lft == $category_Item->lft - 1 )
                    $upable = false;
                if($directParent->rgt == $category_Item->rgt + 1 )
                    $downable = false;
                return new JsonModel(array('success'=>true, "upable"=>$upable, "downable"=>$downable));
            }




        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function upCategoryAction(){
        try{

            $id = $this->params()->fromPost('id');
            if(!$id){
                throw new BusinessException("Chưa truyền id!");
            }

            $categoryTable = $this->getTableFinder()->getCategoryTable(
                AdminSessionHelper::getCurrentLang());
            $category_Item = $categoryTable->getCategory($id);
            $category_Item->upMyPosition();
            return new JsonModel(array('success'=>true));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function downCategoryAction(){
        try{

            $id = $this->params()->fromPost('id');
            if(!$id){
                throw new BusinessException("Chưa truyền id!");
            }

            $categoryTable = $this->getTableFinder()->getCategoryTable(
                AdminSessionHelper::getCurrentLang());
            $category_Item = $categoryTable->getCategory($id);
            $category_Item->downMyPosition();
            return new JsonModel(array('success'=>true));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function removeCategoryAction(){
        try{

            $id = $this->params()->fromPost('id');
            if(!$id){
                throw new BusinessException("Chưa truyền id!");
            }

            $categoryTable = $this->getTableFinder()->getCategoryTable(
                AdminSessionHelper::getCurrentLang());
            $categoryTable->removeCategory($id);
            return new JsonModel(array('success'=>true));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    private function validateSaveCategory($allParams){
        if(!$allParams['code'] ||!$allParams['name'])
            throw new BusinessException('Vui lòng nhập đầy đủ thông tin bắt buộc');
        $categoryTable = $this->getTableFinder()->getCategoryTable(
            AdminSessionHelper::getCurrentLang());

        if(!$allParams['id']){
            $category_Item = $categoryTable->getCategory($allParams['parentId']);
            $sameCodeCategory = $categoryTable->getCategoryByCodeInGroup(
                $category_Item->group_code, $allParams['code']);
            if($sameCodeCategory)
                throw new BusinessException('Đã tồn tại nhóm có mã: '.$allParams['code']);
        }else{
            $category_Item = $categoryTable->getCategory($allParams['id']);
            $sameCodeCategory = $categoryTable->getCategoryByCodeInGroup(
                $category_Item->group_code, $allParams['code']);
            if($sameCodeCategory && $sameCodeCategory->id != $allParams['id'])
                throw new BusinessException('Đã tồn tại nhóm có mã: '.$allParams['code']);
        }
    }

    public function saveCategoryAction(){
        try{
            $this->validateSaveCategory($this->params()->fromPost()) ;
            $code = $this->params()->fromPost('code');
            $name = $this->params()->fromPost('name');
            $description = $this->params()->fromPost('description');
            $parentId = $this->params()->fromPost('parentId');

            $id = $this->params()->fromPost('id');

            $categoryTable = $this->getTableFinder()->getCategoryTable(
                AdminSessionHelper::getCurrentLang());

            if(!$id){
                $data = array("code"=>$code,"name"=>$name,"description"=>$description,"parentId"=>$parentId);
                $id = $categoryTable->addCategory($data);
            }
            else{
                $data = array("id"=>$id, "code"=>$code,"name"=>$name,"description"=>$description);
                $categoryTable->updateCategory($data);
            }

            return new JsonModel(array('success'=>true,'id'=>$id));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }


}